import type {
  MyToDoOptionsPropsType,
  MyToDoOptionsStateType,
  MyToDoOptionsButtonType
} from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElCard, ElTabs, ElTabPane, ElSpace, ElDivider, ElButton } from 'element-plus'
import AliIcon from '~/components/AliIocn'
import OrderInfo from '../components/orderTabs/OrderInfo'
import OperationRecord from '../components/orderTabs/OperationRecord'
import OptionButtonEvent from '../components/orderTabs/optionButtonEvent'
import styles from '../index.module.scss'

export default defineComponent({
  name: 'MyToDoOptions',
  props: ['visible', 'selectedKey', 'selectedValue', 'record', 'cancel'],
  setup (props: MyToDoOptionsPropsType) {
    const operationRecordRef = ref()
    const store = useStore()
    const state = reactive<MyToDoOptionsStateType>({
      activeTabKey: 'info',
      orderInfo: {},
      processRecordList: [],
      optionButtonList: []
    })

    // 获取工单详情 businessKey 就是工单id
    const handleGetOrderInfoByBusinessKey = async () => {
      if (!props.record?.businessKey) return
      const res = await store.dispatch('order/GetOrderInfo', { id: props.record?.businessKey })
      state.orderInfo = res?.data || {}
    }

    // 获取操作记录列表
    const handleGetProcessRecordListByProcessInstanceId = async () => {
      if (!props.record?.processInstanceId) return
      const res = await store.dispatch('toDo/GetToDoProcessRecordList', {
        processInstanceId: props.record?.processInstanceId
      })
      state.processRecordList = res?.data || []
    }

    // 获取待办可操作按钮列表
    const handleGetTodoViewOptionButtonsByTaskId = async () => {
      if (!props.record?.taskId) return
      const res = await store.dispatch('toDo/GetTodoViewOptionButtonList', {
        taskId: props.record?.taskId
      })
      state.optionButtonList = res?.data?.operationList || []
    }

    // 点击操作按钮的回调
    const handleClickOptionButton = (
      identType: MyToDoOptionsButtonType['identType'],
      type: MyToDoOptionsButtonType['type']
    ) => {
      state.clickOptionButtonType = {
        identType,
        operationType: type
      }
    }

    // 初始化时请求数据
    onMounted(() => {
      handleGetProcessRecordListByProcessInstanceId()
      // 只在待办弹框的时候获取操作按钮列表
      if (props.selectedKey === 'agency') handleGetTodoViewOptionButtonsByTaskId()
      Promise.all([handleGetOrderInfoByBusinessKey()]).then(() => {
        // 获取操作列表
        operationRecordRef.value?.searchOperationRecordList()
      })
    })
    return () => (
      <ElCard class={styles['order-card']}>
        <ElSpace class={styles['order-tab-option-btns']}>
          <ElButton text type="primary" onClick={props.cancel}>
            返回上一级&nbsp;
            <AliIcon type="icon-fanhuishangyiji" />
          </ElButton>
        </ElSpace>
        <ElTabs v-model={state.activeTabKey}>
          <ElTabPane name="info" label={`${props.selectedValue}详情`}>
            <OrderInfo
              annexUrlArray={state.orderInfo.annexUrl ? state.orderInfo.annexUrl!.split(',') : []}
              processRecordList={state.processRecordList}
              {...state.orderInfo}
            />
          </ElTabPane>
          <ElTabPane name="operation" label="操作记录" lazy>
            <OperationRecord
              ref={operationRecordRef}
              detail={state.orderInfo}
              processRecordList={state.processRecordList}
            />
          </ElTabPane>
        </ElTabs>
        {!!state.optionButtonList?.length && (
          <>
            <ElDivider />
            <ElSpace class={styles['option-button-list']}>
              {state.optionButtonList?.map((item) => (
                <ElButton
                  key={item.label}
                  type="primary"
                  onClick={() => handleClickOptionButton(item.identType, item.type)}
                >
                  {item.label}
                </ElButton>
              ))}
            </ElSpace>
          </>
        )}
        <OptionButtonEvent
          record={props.record}
          clickOptionButtonType={state.clickOptionButtonType}
          detail={state.orderInfo}
          cancel={props.cancel}
          clearClickOptionButtonType={() => {
            state.clickOptionButtonType = undefined
          }}
        />
      </ElCard>
    )
  }
})
